package com.xjscrm.console.mq.producer;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaBaseDto;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerConversationTalkMsg;
import com.uzai.mobile.collect.api.enums.MicaTalkMsgType;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.utils.MqDelayLevel;
import com.xjscrm.common.utils.MqDelayLevelUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.console.entity.ChatTalkRecord;
import com.xjscrm.console.entity.ChatTalkSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author lucher
 * @date 2024-03-01 10:41
 */
@Slf4j
@Component
public class SendMsgProducer {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送瞬时消息
     *
     * @param micaBaseDto
     * @param topic
     * @author lucher
     * @date 2024/3/6 15:31
     */
    public void pushMsg(MicaBaseDto micaBaseDto, String topic) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(micaBaseDto));
        log.info("--MQ发送消息-topic={}, msg:{}", topic, msg);

        //异步调用MQ发送消息
        rocketMQTemplate.asyncSend(topic, msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("--推送消息-成功--topic={}, msg={}", topic, msg);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("--MQ推送消息-失败--topic={}, msg={}, error:{}", topic, msg, throwable.getMessage());
            }
        }, 3000);
    }

    /**
     * 发送延迟消息
     *
     * @param micaBaseDto
     * @param topic
     * @author lucher
     * @date 2024/3/6 15:31
     */
    @TraceGenerate //注入消息id标签
    public void pushMsgDelay(MicaBaseDto micaBaseDto, String topic) {
        int sumDelay = micaBaseDto.getDelay();
        MqDelayLevel delayLevel = MqDelayLevelUtil.getLevel(sumDelay);
        int mq_max_delay = delayLevel.getDelay();
        int level = delayLevel.getLevel();
        // 剩余延时
        int leftDelay = sumDelay - mq_max_delay;
        if (leftDelay < 0) {
            leftDelay = 0;
        }
        micaBaseDto.setDelay(leftDelay);

        String msg = Tools.getStrEmpty(JSONObject.toJSONString(micaBaseDto));
        log.info("--MQ发送延迟消息-topic={}, msg:{}", topic, msg);

        //封装消息类
        Message<?> message = MessageBuilder.withPayload(msg).build();

        //异步调用MQ发送消息
        rocketMQTemplate.asyncSend(topic, message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("--推送延迟消息-成功--topic={}, msg={}", topic, msg);
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("--MQ推送延迟消息-失败--topic={}, msg={}, error:{}", topic, msg, throwable.getMessage());
            }
        }, 3000, level);
    }


    public void replySessionText(ChatTalkSession talkSession, ChatTalkRecord record) {
        MicaTriggerConversationTalkMsg micaTriggerConversationTalkMsg = new MicaTriggerConversationTalkMsg();

        micaTriggerConversationTalkMsg.setContentType(MicaTalkMsgType.TEXT.getCode());
        micaTriggerConversationTalkMsg.setContent(record.getContent());
        micaTriggerConversationTalkMsg.setWxId(talkSession.getConversationId());

        Long finalTaskId = ObjectUtils.defaultIfNull(record.getId(), IdUtil.getSnowflakeNextId());

        MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerConversationTalkMsg, MicaTriggerType.TRIGGER_CONVERSATION_TALK, item -> {
            item.setReqId(finalTaskId);
            item.setDeviceId(talkSession.getDeviceId());
            item.setDeviceType(talkSession.getDeviceType());
        });
        this.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
    }
}
